//import { parse } from 'qs';
import { routerRedux } from 'dva/router';
import { message } from 'antd';
import _ from 'lodash';
import {
    storeSet,
    loginStatus,
    storeGet,
} from '../utils';
import { setToken } from '../global';
import { login, logout, payCount, chagePsw } from '../services/app';

let isLogin = false;
let loginToken;
setToken(() => loginToken);
const KEY_PATH = 'keyPath';
//const TOKEN = 'token';
const USER = 'user';
const URL = 'url';

export default {
    namespace: 'app',
    state: {
        login: false,
        loading: false,
        user: null,
        baseData: {
            gender: [
                {
                    id: 'gender_id_0',
                    code: '0',
                    name: '未知',
                },
                {
                    id: 'gender_id_1',
                    code: '1',
                    name: '男',
                },
                {
                    id: 'gender_id_2',
                    code: '2',
                    name: '女',
                },
            ],
            roles: [
                {
                    id: '0',
                    code: '0',
                    name: '超级管理员',
                },
                {
                    id: '3',
                    code: '3',
                    name: '店员',
                },
                {
                    id: '2',
                    code: '2',
                    name: '店长',
                },
            ],
            player_type: [
                {
                    id: 'player_type_id_0',
                    code: '0',
                    name: 'VIP会员',
                },
                {
                    id: 'player_type_id_1',
                    code: '1',
                    name: '散客',
                },
            ],
            timeUnit: [
                {
                    id: 'tu_0',
                    name: '分钟',
                    code: 'tu_minute',
                },
                {
                    id: 'tu_1',
                    name: '小时',
                    code: 'tu_hour',
                },
                {
                    id: 'tu_2',
                    name: '天',
                    code: 'tu_day',
                },
                {
                    id: 'tu_3',
                    name: '周',
                    code: 'tu_week',
                },
                {
                    id: 'tu_4',
                    name: '月',
                    code: 'tu_month',
                },
                {
                    id: 'tu_5',
                    name: '季度',
                    code: 'tu_quarter',
                },
                {
                    id: 'tu_6',
                    name: '年',
                    code: 'tu_year',
                },
            ],
            sumUnit: [
                {
                    id: 'cu_0',
                    name: '元',
                    code: 'cu_yuan',
                },
            ],
            /**
             * 目前模板数据先固化在前端,并且仅有一种模板
             * 所有的计费类型都由此模板衍生(在管理端-BS配置,在设备端-CS使用)
             * 模板的数据主要是共前端根据模板内容渲染表单使用的
             */
            chargeTypeModule: [
                {
                    id: 'ctm_0000',         //模版id
                    name: '计时消费',        //模版名称
                    code: 'ct_by_time',     //模版编码
                    cont: {                 //模版内容
                        price: {
                            uiType: 'input',        //ui类型是input
                            valueType: 'number',    //数据类型是number(int)
                            required: true,         //是必填项
                            defaultValue: 0,        //默认值是 0
                        },
                        sumUnit: {
                            uiType: 'select',
                            valueType: 'object',
                            required: true,
                            defaultValue: {
                                id: 'cu_0',
                                name: '元',
                            },
                        },
                        timeUnit: {
                            uiType: 'select',
                            valueType: 'object',
                            required: true,
                            defaultValue: {
                                id: 'tu_0',         //时长单位id（string）
                                name: '分钟',         //时长单位名称（string）
                            },
                        },
                        deposit: {                  //押金，单位元（int）
                            uiType: 'input',
                            valueType: 'number',
                            required: true,
                            defaultValue: 100,
                        },
                        numberOfPeople: {           //允许参与人数上限（int）
                            uiType: 'input',
                            valueType: 'number',
                            required: true,
                            defaultValue: 100,
                        },
                    },
                }
            ],
            /**
             * 计费类型实例列表
             * 以下数据为管理者(店主)通过上面的计费类型模板生成的实例数据
             * 这些数据共CS端绑定至游戏,为游戏提供计费规则定义
             * */
            chargeType: [
                {
                    id: 'ct_0000',           //计费类型实例id
                    name: '计费类型1',         //计费类型实例名称
                    moduleId: 'ctm_0000',    //所属模版id
                    moduleName: '计时消费',    //所属模版名称
                    cont: {
                        price: 10,           //单价（int）
                        sumUnit: {          //单价金额单位（obj）
                            id: 'cu_0',     //单价金额单位id（string）
                            name: '元',      //单价金额单位名称（string）
                        },
                        timeUnit: {          //单价时长单位（obj）
                            id: 'tu_0',      //时长单位id（string）
                            name: '分钟',    //时长单位名称（string）
                        },
                        deposit: 100,        //押金，单位元（int）
                        numberOfPeople: 2,   //允许参与人数上限（int）
                    }
                },
                {
                    id: 'ct_0001',           //计费类型实例id
                    name: '计费类型2',                //计费类型实例名称
                    moduleId: 'ctm_0000',    //所属模版id
                    moduleName: '计时消费',    //所属模版名称
                    cont: {
                        price: 20,           //单价（int）
                        sumUnit: {          //单价金额单位（obj）
                            id: 'cu_0',     //单价金额单位id（string）
                            name: '元',      //单价金额单位名称（string）
                        },
                        timeUnit: {          //单价时长单位（obj）
                            id: 'tu_0',      //时长单位id（string）
                            name: '分钟',    //时长单位名称（string）
                        },
                        deposit: 300,        //押金，单位元（int）
                        numberOfPeople: 4,   //允许参与人数上限（int）
                    }
                },
            ],
            income_type: [
                {
                    id: 'income_type_0',
                    name: '散客充值',
                },
                {
                    id: 'income_type_1',
                    name: '会员充值',
                },
                {
                    id: 'income_type_2',
                    name: '实物消费',
                },
                {
                    id: 'income_type_3',
                    name: '不可控游戏消费',
                },
                {
                    id: 'income_type_4',
                    name: '退款',
                },
            ],
            sale_type: [
                {
                    id: 'sale_type_0',
                    name: '游戏消费',
                    code: 'game_sale',
                },
                {
                    id: 'sale_type_1',
                    name: '实物消费',
                    code: 'solid_sale',
                },
            ],
            pay_type: [
                {
                    id: 'pay_type_0',
                    name: '微信支付',
                    code: 'weixinpay',
                },
                {
                    id: 'pay_type_1',
                    name: '支付宝支付',
                    code: 'alipay',
                },
                {
                    id: 'pay_type_2',
                    name: '信用卡支付',
                    code: 'credit_card',
                },
                {
                    id: 'pay_type_3',
                    name: '现金支付',
                    code: 'cash',
                },
            ],
            eventType: [
                {
                    id: 'event_0000',
                    name: '充就送',
                    code: 'charge_gift',
                },
            ],
        },
        menu: [
            {
                name: '店铺管理',
                code: 'store',
                ico: 'home',
                children: [
                    {
                        name: '店铺信息',
                        code: 'store',
                        url: '/store/info',
                        ico: 'home',
                    },
                    {
                        name: '人员管理',
                        code: 'employee',
                        url: '/store/employee',
                        ico: 'team',
                    },
                    {
                        name: '设备管理',
                        code: 'device',
                        url: '/store/device',
                        ico: 'hdd',
                    },
                ],
            },
            {
                name: '财务管理',
                code: 'finance',
                ico: 'bank',
                children: [
                    {
                        name: '收入明细',
                        code: 'income',
                        url: '/financial/orders'
                    },
                    {
                        name: '收入报表',
                        code: 'sale',
                        url: '/financial/income'
                    },
                    {
                        name: 'VIP卡管理',
                        code: 'vipCard',
                        url: '/financial/cards'
                    },
                ]
            },
            {
                name: '运营报表',
                code: 'operate',
                ico: 'pie-chart',
                children: [
                    {
                        name: '游戏运行报表',
                        ico: 'bar-chart',
                        code: 'games',
                        url: '/analysis/games'
                    },
                    {
                        name: '设备运行报表',
                        ico: 'line-chart',
                        code: 'devices',
                        url: '/analysis/devices'
                    },
                ]
            },
        ],
        currentMenuKey: '',
        loginButtonLoading: false,
        changeInfo: false,
        pwV: false,
    },
    subscriptions: {
        setup(args) {
            const { dispatch, history } = args;
            history.listen(({ pathname }) => {
                dispatch({
                    type: 'parsePathname',
                    pathname,
                });
                if (!isLogin) {
                    if (loginStatus()) {
                        dispatch({
                            type: 'reLogin',
                        });
                    } else if (pathname !== '/') {
                        dispatch(routerRedux.push({
                            pathname: '/'
                        }));
                    }
                    if (pathname !== '/') {
                        storeSet(URL, pathname);
                    }
                } else if (pathname === '/') {
                    dispatch({
                        type: 'reLogin',
                    });
                }
            });
        }
    },
    effects: {
        * parsePathname({ pathname }, { select, put }) {
            const { menu = [] } = yield select((state) => state.app);
            const target = _.find(menu, ['url', pathname]);
            if (target) {
                const { id, pid } = target;
                yield put({
                    type: 'jump',
                    payload: {
                        keyPath: [id, pid],
                        url: pathname,
                    },
                    needJump: false,
                });
            }
        },
        * setMenu({ keyPath }, { put }) {
            if (!keyPath) {
                return;
            }
            yield put({
                type: 'upState',
                payload: {
                    keyPath,
                    openKey: keyPath[1],
                },
            });
        },
        * jump({ payload: { keyPath, url }, needJump = true }, { put }) {
            yield put({
                type: 'setMenu',
                keyPath,
            });
            if (needJump) {
                yield put(routerRedux.push({
                    pathname: url,
                }));
            }
            storeSet(KEY_PATH, keyPath);
        },
        * getKeyPath({ payload }, { put, call }) {
            const keyPath = yield call(storeGet, KEY_PATH);
            if (keyPath && keyPath[0]) {
                yield put({
                    type: 'setMenu',
                    keyPath,
                });
            }
        },
        * login({ payload: { ...userInfo } }, { call, put }) {
            const { data, code, msg } = yield call(login, userInfo);
            if (code === 1) {
                isLogin = true;
                // const { user } = data;
                storeSet(USER, data);
                yield put({
                    type: 'upState',
                    payload: {
                        user: data,
                        login: true
                    },
                });
                yield put({
                    type: 'jump',
                    payload: {
                        keyPath: ['store'],
                        url: '/store',
                    },
                });
                yield put({
                    type: 'getKeyPath',
                });
            } else {
                message.error(msg);
            }
        },
        * reLogin(payload, { put, select }) {
            const { login } = select(state => state.app);
            if (!login) {
                const user = storeGet(USER);
                yield [
                    put({
                        type: 'upState',
                        payload: {
                            user,
                            login: true,
                        },
                    }),
                    put({
                        type: 'getKeyPath',
                    }),
                ];
                isLogin = true;
            }
        },
        * logout(payload, { call, put }) {
            const { code, msg } = yield call(logout);
            if (code === 1) {
                yield put(routerRedux.push({
                    pathname: '/store',
                }));
            } else {
                message.error(msg);
            }
        },
        * updatePersonalInfo({ payload: { alipay } }, { put, call}) {
            const { code, msg } = yield call(payCount, {payeeAccount: alipay});
            if (code === 1) {
                message.success(msg);
                yield put({
                    type: 'upState',
                    payload: {
                        changeInfo: false,
                    },
                });
            } else {
                message.error(msg);
            }
        },
        * changePassword({ payload: { old, newPw, rePw } }, { put, call }) {
            console.log('saf');
            const { code, msg } = yield call(chagePsw, { oldPass: old, password: newPw });
            if (code === 1) {
                yield put({
                    type: 'upState',
                    payload: {
                        pwV: false,
                    },
                });
                message.success(msg);
            } else {
                message.error(msg);
            }
        },
    },
    reducers: {
        upState(state, { payload }) {
            return {
                ...state,
                ...payload,
            };
        },
        loginSuccess(state, action) {
            return {
                ...state,
                ...action.payload,
                login: true,
                loginButtonLoading: false
            };
        },
        logoutSuccess(state) {
            return {
                ...state,
                login: false
            };
        },
        loginFail(state) {
            return {
                ...state,
                login: false,
                loginButtonLoading: false
            };
        },
        showLoading(state) {
            return {
                ...state,
                loading: true
            };
        },
        hideLoading(state) {
            return {
                ...state,
                loading: false
            };
        },
    }
};
